from flask import render_template, request, jsonify
from . import classification_bp
from ..utils.stats import record_api_call
import requests
import base64
import json
import urllib.parse

# 百度云API配置
API_KEY = 'ZWsM40uWHibmA6hu4nct354X'
SECRET_KEY = 'dmJoOzQLISTBLooGcnxNsYaetBpfove0'

def get_access_token():
    """获取百度AI平台的access_token"""
    url = "https://aip.baidubce.com/oauth/2.0/token"
    params = {
        "grant_type": "client_credentials",
        "client_id": API_KEY,
        "client_secret": SECRET_KEY
    }
    response = requests.post(url, params=params)
    if response:
        return response.json().get("access_token")
    return None

@classification_bp.route('/')
def index():
    return render_template('modules/image_classification.html')

@classification_bp.route('/process', methods=['POST'])
def process():
    # 记录API调用
    record_api_call('classification')
    
    if 'image' not in request.files and 'url' not in request.form:
        return jsonify({'success': False, 'message': '需要提供图片文件或图片URL'})
    
    try:
        params = {}
        
        # 处理图片文件上传
        if 'image' in request.files:
            file = request.files['image']
            if file.filename == '':
                return jsonify({'success': False, 'message': '没有选择文件'})
            
            # 读取图片并转为base64
            image = file.read()
            image_base64 = base64.b64encode(image).decode('utf-8')
            # 直接使用base64编码，不需要URL编码
            params["image"] = image_base64
        
        # 处理图片URL
        elif 'url' in request.form:
            params["url"] = request.form['url']
        
        # 添加可选参数
        if 'baike_num' in request.form:
            params["baike_num"] = int(request.form['baike_num'])
        
        # 获取access_token
        access_token = get_access_token()
        if not access_token:
            return jsonify({
                'success': False,
                'message': '获取access_token失败'
            })
        
        # 调用通用物体和场景识别接口
        url = f'https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general?access_token={access_token}'
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        
        # 打印请求参数用于调试
        print("Request params:", params)
        
        response = requests.post(url, data=params, headers=headers)
        
        # 打印响应内容用于调试
        print("Response:", response.text)
        
        # 处理响应
        if response.status_code == 200:
            result = response.json()
            if 'error_code' in result:
                return jsonify({
                    'success': False,
                    'message': f"API错误: {result.get('error_msg', '未知错误')}"
                })
            
            # 确保返回的数据格式正确    
            return jsonify({
                'success': True,
                'result': {
                    'result': result.get('result', [])  # 确保result字段存在
                }
            })
        else:
            return jsonify({
                'success': False,
                'message': 'API请求失败'
            })
            
    except Exception as e:
        print(f"Error processing image: {str(e)}")
        return jsonify({
            'success': False,
            'message': '处理图片时发生错误'
        }) 